

<template>
  <div class="pieChart" :id="id" />
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    dataList: {
      type: Array,
      default: () => [
        {
          value: 100,
          name: "0-40岁",
        },
        {
          value: 23,
          name: "40-50岁",
        },
        {
          value: 23,
          name: "50-60岁",
        },
        {
          value: 23,
          name: "60-70岁",
        },
      ],
    },
    id: {
      type: String,
      default: "pieChart",
    },
    title: {
      type: String,
      default: "年龄段分布",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  watch: {
    dataList: {
      handler() {
        this.$nextTick(() => {
          this.initChart();
        });
      },
      deep: true,
    },
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  destroyed() {
    clearInterval(this.setInter);
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el);
      this.chart.showLoading({
        text: "loading",
        color: "rgba(20, 149, 247, 0.7)",
        textColor: "#000",
        maskColor: "rgba(255, 255, 255, 0.2)",
        zlevel: 0,
      });
      window.addEventListener("resize", this.chart.resize);
      const option = {
        // color: ["#ff5876", "#01EEF6"],
        legend: {
          // orient: "vertical",
          left: "right",
          textStyle: {
            color: "#000",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "20px",
        },
        title: {
          text: this.title,
          textStyle: {
            fontSize: 16,
            color: "#000",
          },
        },
        tooltip: {
          trigger: "item",
        },
        xAxis: {
          type: "category",
          data: this.dataList.map((item) => item.projectName),
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: this.dataList,
            type: "bar",
            barWidth: 35,
            label: {
              show: true,
              position: "top",
            },
          },
        ],
      };
      this.chart.setOption(option);
      setTimeout(() => {
        this.chart.hideLoading();
      }, 1000);
    },
  },
};
</script>

<style lang="less" scoped>
.pieChart {
  width: 100%;
  height: 400px;
}
</style>
